<?php

namespace App\Http\Controllers;

use App\Common\JsonTrait;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Log;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests,JsonTrait;

    public function __construct()
    {
    }

    public function callAction($method, $parameters)
    {
        if (method_exists($this, 'preAction')) {
            call_user_func_array([$this, 'preAction'], $parameters);
        }

        $response = parent::callAction($method, $parameters);

        $this->logResponse($response);

        return $response;
    }

    public function preAction()
    {
        $request = request();

        $logContext = [
            'method' => $request->getMethod(),
            'url' => $request->fullUrl(),
            'ip' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'input' => $request->all(),
        ];

        Log::channel('api')->info('API request received', $logContext);

        return true;
    }

    protected function logResponse($response): void
    {
        $request = request();

        if ($response instanceof Response || $response instanceof JsonResponse) {
            $content = $response->getContent();
        } elseif (is_array($response) || is_object($response)) {
            $content = json_encode($response, JSON_UNESCAPED_UNICODE);
        } else {
            $content = (string) $response;
        }

        $logContext = [
            'method'   => $request->getMethod(),
            'url'      => $request->fullUrl(),
            'response' => $content,
        ];

        Log::channel('api')->info('API response sent', $logContext);
    }
}
